import "reflect-metadata";
import { createConnection } from "typeorm";
import { Notice } from "../entity/Notice";
import { Request, Response } from "express";

const moment = require('moment-timezone');

const connR = createConnection("login");

export function noticeRoute(app: any) {

    app.put('/api/notice', function (req: Request, res: Response) {

        connR.then(async connection => {

            let notice = new Notice();
            notice.content = req.body.content;
            notice.time = req.body.time
            notice.created_at = moment().format();
            notice.updated_at = notice.created_at;
            await connection.getRepository(Notice).save(notice);

            res.send({ success: true })

        }).catch(error => console.log(error));
    })

    app.delete('/api/notice/:id', function (req: Request, res: Response) {

        connR.then(async connection => {

            await connection.getRepository(Notice).delete(req.params.id);
            res.send({ success: true })

        }).catch(error => console.log(error));
    })

    app.post('/api/notice/:id', function (req: Request, res: Response) {

        connR.then(async connection => {


            let repository = connection.getRepository(Notice);
            let notice = await repository.findOne(req.params.id);
            notice.content = req.body.content;
            notice.time = req.body.time;
            notice.updated_at = moment().format();
            await connection.getRepository(Notice).save(notice);

            res.send({ success: true })

        }).catch(error => res.send({ success: false, msg: error }));
    })

    app.get('/api/notice/:id', function (req: Request, res: Response) {

        connR.then(async connection => {

            let data = await connection.getRepository(Notice).findOne(req.params.id);
            data.time = moment(data.time).format();
            res.send(data)

        }).catch(error => console.log(error));
    })

    app.get('/api/notices', function (req: Request, res: Response) {

        const pageNum = 20

        let page = req.query.page
        if (!page) { page = 1 }

        connR.then(async connection => {

            let data = await connection.getRepository(Notice).find({ order: { time: 'DESC' }, skip: (page - 1) * pageNum, take: pageNum });

            data.forEach(element => {

                element.time = moment(element.time).format();
            });

            res.send(data)

        }).catch(error => console.log(error));
    })

    app.get('/notice', function (req: Request, res: Response) {

        connR.then(async connection => {

            let data = await connection.getRepository(Notice).createQueryBuilder().select("COUNT(*) AS c").getRawOne();
            res.render('server/notice', { total: data.c })

        }).catch(error => console.log(error));

    })
}




